//
//  RemindMeViewController.m
//  忘不了
//
//  Created by rimi on 16/7/8.
//  Copyright © 2016年 handuan. All rights reserved.
//

#import "RemindMeViewController.h"
#import "RemindMeTableViewCell.h"
#import "DetailRemindMeViewController.h"
#import "SDAutoLayout.h"
#import "FinalViewController.h"

@interface RemindMeViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)NSMutableArray *headingArray;
@property (nonatomic,strong)NSMutableArray *timeArray;

@property (nonatomic,strong)UIButton *writeButton;

@property (nonatomic,strong) UIImageView *bgImageView;

@end
static RemindMeViewController * RVC;
@implementation RemindMeViewController


- (void)dealloc
{
    NSLog(@"%@ dealloc :%@", [self class], self);
}

- (void)viewDidLoad {
//    RVC = self;
    [super viewDidLoad];
    self.title = @"备忘录";
    self.view.backgroundColor = [UIColor whiteColor];
    [self loadUI];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSArray *result = [[NSUserDefaults standardUserDefaults] objectForKey:@"rememberList"];
    if (result != nil) {
        self.dataSource = result.mutableCopy;
    }else{
        self.dataSource = @[].mutableCopy;
    }
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //    selectDateFormatter.dateFormat = @"yy:MM:dd"; //设置时间和日期的格式
    [formatter setDateFormat:@"MM-dd H:mm"];
    NSString *dateString = [formatter stringFromDate:date];
    
    
    for (NSInteger index= 0; index < self.dataSource.count; index ++) {
        NSInteger number = [self compareDate:self.dataSource[index][@"data"] withDate:dateString];
        if (number == 1) {
            //                self.dataSource[index][@"image"] = @"pass印章";
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:self.dataSource[index]];
            [dic setValue:@"pass印章" forKey:@"image"];
            [self.dataSource removeObjectAtIndex:index];
            [self.dataSource insertObject:dic atIndex:index];
            [self.tableView reloadData];
        }
    }
    
    
    NSLog(@"%@",self.dataSource);
    [self.tableView reloadData];
}

-(NSInteger)compareDate:(NSString*)date01 withDate:(NSString*)date02{
    NSInteger ci;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"MM-dd H:mm"];
    NSDate *dt1 = [[NSDate alloc] init];
    NSDate *dt2 = [[NSDate alloc] init];
    dt1 = [df dateFromString:date01];
    dt2 = [df dateFromString:date02];
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result)
    {
            //date02大
        case NSOrderedAscending: ci=1; break;
            //date01大
        case NSOrderedDescending: ci=-1; break;
            //date02=date01
        case NSOrderedSame: ci=0; break;
        default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
    }
    return ci;
}

- (void)loadUI {
    _bgImageView = [[UIImageView alloc]init];
    [_bgImageView setImage:[UIImage imageNamed:@"s"]];
    [self.view addSubview:_bgImageView];
    _bgImageView.sd_layout.topSpaceToView(self.view,0).leftSpaceToView(self.view,0).rightSpaceToView(self.view,0).bottomSpaceToView(self.view,0);
    
    
    _tableView = [[UITableView alloc]init];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 100;
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];
    _tableView.sd_layout.topSpaceToView(self.view,64).rightSpaceToView(self.view,0).leftSpaceToView(self.view,0).bottomSpaceToView(self.view,0);
    
    _writeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_writeButton setTitle:@"+" forState:UIControlStateNormal];
    _writeButton.layer.cornerRadius = 25;
    _writeButton.layer.shadowOffset = CGSizeMake(3, 3);
    _writeButton.layer.shadowOpacity = 0.5;
    _writeButton.backgroundColor = [UIColor colorWithRed:0.9216 green:0.8902 blue:0.749 alpha:1.0];
    [_writeButton addTarget:self action:@selector(writeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_writeButton];
    _writeButton.sd_layout.rightSpaceToView(self.view,50).bottomSpaceToView(self.view,50).widthIs(50).heightIs(50);
    [self addObserver:self forKeyPath:@"userDate" options:NSKeyValueObservingOptionNew context:nil];
}
+(RemindMeViewController *)getVC{
    
    if (RVC == nil) {
        RVC = [[RemindMeViewController alloc] init];
    }
    
    return RVC;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if([keyPath isEqual:@"userDate"] && object == self) {
        for (NSInteger index= 0; index < self.dataSource.count; index ++) {
            if ([change[@"new"] isEqualToString:self.dataSource[index][@"data"] ]) {
//                self.dataSource[index][@"image"] = @"pass印章";
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:self.dataSource[index]];
                [dic setValue:@"pass印章" forKey:@"image"];
                [self.dataSource removeObjectAtIndex:index];
                [self.dataSource insertObject:dic atIndex:index];
                [self.tableView reloadData];
            }
        }
    }
}
#pragma mark -- UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifer = @"RemindMeTableViewCell";
    RemindMeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
    if (!cell) {
        cell = [[RemindMeTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifer];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        NSDictionary *dic = self.dataSource[indexPath.row];
        cell.headingLabel.text = dic[@"heading"];
        cell.timeLabel.text = dic[@"data"];
        [cell.passImageView setImage:[UIImage imageNamed:self.dataSource[indexPath.row][@"image"]]];
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
    
}

//配置删除按钮的title
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

//提交删除状态
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        NSMutableDictionary *dic = self.dataSource[indexPath.row];
        NSString *string = dic[@"data"];
        NSLog(@"%@",string);
        NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
        for (UILocalNotification *notif in notificationArray) {
            if ([string isEqualToString:notif.userInfo[@"alarmID"]]) {
                [[UIApplication sharedApplication] cancelLocalNotification:notif];
                NSLog(@"删除后剩余的的通知：%@",[[UIApplication sharedApplication] scheduledLocalNotifications]);
                break;
            }
        }
        //1.删除数据源
        
        [self.dataSource removeObjectAtIndex:indexPath.row];
        [[NSUserDefaults standardUserDefaults]setObject:self.dataSource forKey:@"rememberList"];
        //2.删除表格行视图
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取消选中颜色
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([self.dataSource[indexPath.row][@"image"] isEqualToString:@"pass印章"]) {
        FinalViewController *finalViewController = [[FinalViewController alloc]init];
        finalViewController.dic2 = self.dataSource[indexPath.row];
        finalViewController.number = -1;
        [self presentViewController:finalViewController animated:YES completion:nil];
        
    }else{
        DetailRemindMeViewController *detailRemindMeViewController = [[DetailRemindMeViewController alloc]init];
        detailRemindMeViewController.dic1 = self.dataSource[indexPath.row];
        detailRemindMeViewController.dateString = self.dataSource[indexPath.row][@"data"];
        detailRemindMeViewController.number = indexPath.row;
        detailRemindMeViewController.dataSource = self.dataSource;
        [self.navigationController pushViewController:detailRemindMeViewController animated:YES];
    }
}

#pragma mark -- Action

- (void)writeButtonPressed:(UIButton *)sender{
    DetailRemindMeViewController *detailRemindMeViewController = [[DetailRemindMeViewController alloc]init];
    detailRemindMeViewController.dataSource = self.dataSource;
    detailRemindMeViewController.number = -1;
    NSLog(@"%@",detailRemindMeViewController.dataSource);
    [self.navigationController pushViewController:detailRemindMeViewController animated:YES];
}



@end
